﻿#include "SQLiteLog.h"
#include <QtSql/QSqlError>
#include <QVariant>
#include <QSqlQuery>
#include <QDateTime>
#include <QDebug>
#include <QDir>
SQLiteLog::SQLiteLog()
{
    m_database = QSqlDatabase::addDatabase("QSQLITE");
}

bool SQLiteLog::loadSettings(QSettings &settings)
{
    QString dataPath = settings.value("Path/SQLiteFile", "D:/Data/logging.sqlite").toString();
    QDir dir;
    if(!dir.exists(dataPath))
    {
        m_database.setDatabaseName(dataPath);
        m_database.open();
        QSqlQuery query;
        query.prepare("CREATE TABLE [Data]( [Time] DATETIME NOT NULL, "
                                            "[Robot] TEXT NOT NULL, "
                                            "[Side] TEXT NOT NULL, "
                                            "[panelID] TEXT NOT NULL, "
                                            "[ShiftX] REAL NOT NULL, "
                                            "[ShiftY] REAL NOT NULL, "
                                            "[Theta] REAL NOT NULL, "
                                            "[Score] REAL NOT NULL,"
                                            "[RecipeName] TEXT);");
        return query.exec();
    }
    else
    {
        m_database.setDatabaseName(dataPath);
        if (!m_database.open())
        {
            qDebug() << "m_database.open() fail, dataPath = " << dataPath;
            return false;
        }
    }
    return true;
}

bool SQLiteLog::log(int channel, int side, QString panelID, double x, double y, double theta, double score, QString recipeName)
{
    QString timeString = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString robot = (channel == 0) ? "LeftRobot" : "RightRobot";
    QString sd = (side == 0) ? "Left" : "Right";
    QSqlQuery query;
    query.prepare("INSERT INTO Data (Time, Robot, Side, panelID, ShiftX, ShiftY, Theta, Score, RecipeName) "
                  "VALUES (:Time, :Robot, :Side, :panelID, :ShiftX, :ShiftY, :Theta, :Score, :RecipeName);");

    query.bindValue(":Time", timeString);
    query.bindValue(":Robot", robot);
    query.bindValue(":Side", sd);
    query.bindValue(":panelID", panelID);
    query.bindValue(":ShiftX", x);
    query.bindValue(":ShiftY", y);
    query.bindValue(":Theta", theta);
    query.bindValue(":Score", score);
    query.bindValue(":RecipeName", recipeName);

    return query.exec();
}
